import { makeAutoObservable } from 'mobx';
import { User, UserFormValues } from './userTypes';
import { getUserList, createUser, updateUser, getInfo, deleteUser ,getActiveRole, getActiveUser, batchUpdatePwd, resetPassword} from '../../../../../apis/backhub/user';
import { message } from 'antd';

class UserStore {
  users: User[] = [];
  modalVisible = false; // 弹窗显示状态
  editingUser: User | undefined = undefined; // 当前编辑的用户，undefined表示新建
  loading = false;
  roleValues: any;
  userValues: any;
  userOptions = [];

  constructor() {
    makeAutoObservable(this);
  }

  // 获取用户列表
  fetchUsers = async () => {
    this.loading = true;
    try {
      const response = await getUserList();
      this.users = (response as any).data;
    } catch (error) {
      console.error('获取用户列表失败:', error);
    } finally {
      this.loading = false;
    }
  };

  // 获取角色列表
  getActiveRole = async () => {
    this.loading = true;
    try {
      const response = await getActiveRole();
      this.roleValues = (response as any).data;
    } catch (error) {
      console.error('获取用户列表失败:', error);
    } finally {
      this.loading = false;
    }
  };


  // 获取人员列表
  getActiveUser = async () => {
    this.loading = true;
    try {
      this.userOptions=[];
      const response = await getActiveUser();
      this.userValues = (response as any).data;
      this.userValues && Object.entries(this.userValues)
        .filter(([id]) => String(id) !== '1') 
        .filter(([id]) => String(id) !== '2') 
        .forEach(([, config]) => {
          this.userOptions.push(config);
        });
    } catch (error) {
      console.error('获取用户列表失败:', error);
    } finally {
      this.loading = false;
    }
  };


  // 获取用户
  getUser = async (id: string) => {
    try {
      this.loading = true;
      const response = await getInfo(id);
      this.editingUser =  (response as any).data;
      return this.editingUser; // 返回获取到的用户数据
    } catch (error) {
      console.error('获取用户失败:', error);
      throw error;
    } finally {
      this.loading = false;
    }
  };

  batchUpdatePwd = async (data: any) => {
    try {
      this.loading = true;
      const response = await batchUpdatePwd(data);
      if((response as any)?.status){
        message.success('更新成功');
      }
      this.editingUser =  (response as any).data;
      return this.editingUser; // 返回获取到的用户数据
    } catch (error) {
      console.error('获取用户失败:', error);
      throw error;
    } finally {
      this.loading = false;
    }
  };

  resetPwd = async (id: string) => {
    try {
      this.loading = true;
      let data = {"ids":[id], "password":"123456"};
      const response = await resetPassword(data);
      if((response as any)?.status){
        message.success('重置成功');
      }
    } catch (error) {
      console.error('重置密码失败:', error);
      throw error;
    } finally {
      this.loading = false;
    }
  };

  // 显示创建弹窗
  showCreateModal = () => {
    this.editingUser = undefined;
    this.modalVisible = true;
  };

  // 显示编辑弹窗
  showEditModal = (func: User) => {
    this.editingUser = func;
    this.modalVisible = true;
  };

  // 隐藏弹窗
  hideModal = () => {
    this.modalVisible = false;
    this.editingUser = undefined;
  };

  // 保存用户
  saveUser = async (values: UserFormValues) => {
    try {
      if (this.editingUser && this.editingUser.id) {
        const response = await updateUser(this.editingUser.id, values);
        if((response as any)?.status){
            message.success('更新成功');
        }
      } else {
        const response = await createUser(values);
        if((response as any)?.status){
            message.success('创建成功');
        }
      }
      this.hideModal();
      this.fetchUsers();
    } catch (error) {
      console.error('保存用户失败:', error);
    }
  };

  // 删除用户
  deleteUser = async (id: string) => {
    try {
      await deleteUser(id);
      this.fetchUsers();
    } catch (error) {
      console.error('删除用户失败:', error);
    }
  };
}

export const userStore = new UserStore();